<?php
namespace admin\controllers;

use ijony\helpers\File;
use ijony\helpers\Folder;
use ijony\helpers\Image;
use ijony\helpers\Utils;
use Yii;
use yii\base\ErrorException;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use yii\web\Controller as BaseController;
use yii\web\Response;
use yii\web\UploadedFile;

/**
 * 配合 Uploadifive 使用的上传类
 */
class UploadController extends BaseController
{

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'image' => ['post'],
                ],
            ],
        ];
    }

    public function init()
    {
        parent::init();

        Yii::$app->response->format = Response::FORMAT_JSON;
    }

    /**
     * @return array
     * @throws \Imagine\Image\InvalidArgumentException
     */
    public function actionImage()
    {
        $request = Yii::$app->request;
        $timestamp = $request->post('timestamp');
        $token = $request->post('token');
        $width = $request->post('width');
        $height = $request->post('height');
        $verifyToken = md5('biffar_' . $timestamp);

        try{
            $file = UploadedFile::getInstanceByName('Filedata');

            if(!$file || $token != $verifyToken){
                throw new ErrorException('参数错误！');
            }

            $imgInfo = pathinfo($_FILES['Filedata']['name']);

            if(!in_array($file->getExtension(), ['jpg', 'gif', 'png', 'jpeg'])){
                throw new ErrorException('文件格式错误！' . $file->getExtension());
            }

            $newImg = File::newBufferFile($file->getExtension(), Yii::$app->user->id);

            if(!$file->saveAs(Folder::getStatic($newImg))){
                throw new ErrorException($imgInfo['basename'] . '上传失败！');
            }

            $newImgs[] = $newImg;

            $return['error'] = 0;
            $return['images'] = array_map(function($image)use($width, $height){
                $return['thumb'] = Image::getImg($image, $width, $height);
                $return['image'] = $image;

                return $return;
            }, $newImgs);

            return $return;

        }catch (ErrorException $e){
            return [
                'error' => 1,
                'msg' => $e->getMessage()
            ];
        }
    }
}
